﻿

Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_BanHang_Edit
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            If Not Request.QueryString("Id").ToString.Equals("0") Then
                Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
                If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                    ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
                Else
                    Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
                End If
                '  txtOrderDate.Text = Now.Date.ToString("dd/MM/yyyy")
                BindListStore()
                ddlStore.Attributes.Add("onchange", "return GenerateOrderId()")
                ShowOrderDetail()
                hidID.Value = Request.QueryString("Id")

            End If

        End If

    End Sub
    Protected Sub ShowOrderDetail()
        Using data As New VSEntities
            hidID.Value = Request.QueryString("Id")
            Dim p As BanHang = (From q In data.BanHangs Where q.Id = hidID.Value Select q).SingleOrDefault

            If Not p Is Nothing Then


                txtOrderDate.Text = Format(IIf(IsNothing(p.BanHangDate) = True, "", p.BanHangDate), "dd/MM/yyyy")


                txtMaDonHang.Text = IIf(IsNothing(p.BanHangId) = True, "", p.BanHangId)
                hidOrderId.Value = txtMaDonHang.Text

                txtCustomerCode.Text = IIf(IsNothing(p.CustomerName) = True, "", p.CustomerName)
                ddlStore.SelectedValue = p.StoreId
                txtAddress.Text = IIf(IsNothing(p.Address) = True, "", p.Address)

                txtEmail.Text = IIf(IsNothing(p.Email) = True, "", p.Email)
                txtPhone.Text = IIf(IsNothing(p.Phone) = True, "", p.Phone)

                If Not p.GrossAmount Is Nothing Then
                    lblGrossAmount.Text = CType(p.GrossAmount, Double).ToString("##,###")
                End If

                'set session Session("curSA")
                'Session("curSA") = temp.Value



                'neu co' input request date
                If Not p.IsEditBanHangDate Is Nothing AndAlso p.IsEditBanHangDate = True Then
                    chkEditDelivery.Checked = True
                    txtOrderDate.Enabled = True
                Else
                    chkEditDelivery.Checked = False
                    txtOrderDate.Enabled = False
                End If
                ' Excute_Javascript("ShowDiv();", Me.Page, True)
            End If



        End Using
    End Sub

    Protected Sub BindListStore()
        Dim userId As Integer = Session("UserId")
        Using Data As New VSEntities
            Dim p = (From q In Data.Stores Join k In Data.UserStores On q.StoreId Equals k.StoreId Where k.UserId = userId Select q Order By q.Title).ToList

            With ddlStore
                .DataValueField = "StoreId"
                .DataTextField = "Title"
                .DataSource = p
                .DataBind()

                .Items.Insert(0, New ListItem("--- Chọn ---", ""))

            End With
        End Using
    End Sub

    Protected Sub btnSaveOrderDetail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveOrderDetail.Click
        If Session("Username") = Nothing Then
            Excute_Javascript("Alertbox('Bạn chưa đăng nhập vào hệ thống. vui lòng đăng nhập !');window.location ='../../Login.aspx';", Me.Page, True)
            Exit Sub
        End If
        Using data As New VSEntities
            'Kiem tra don hang da ton tai chua
            Dim count = (From q In data.BanHangs Where q.BanHangId = txtMaDonHang.Text.Trim Select q).Count

            If count > 1 Then
                Excute_Javascript("AlertBox('Số đơn hàng đã tồn tại.');", Me.Page, True)
                Exit Sub
            End If
            ' Lưu thông tin  Order

            Dim p As New VSModel.BanHang

            Try
                p = (From q In data.BanHangs Where q.BanHangId = hidOrderId.Value).FirstOrDefault

                p.StoreId = ddlStore.SelectedValue
                p.BanHangId = txtMaDonHang.Text
                p.CustomerName = txtCustomerCode.Text
                p.Address = txtAddress.Text
                p.Phone = txtPhone.Text
                p.Email = txtEmail.Text
                p.Modified = Now
                p.Modifier = Session("UserName")

                p.BanHangDate = StringToDate(txtOrderDate.Text)

                data.SaveChanges()
                hidID.Value = p.Id
                'xoa order detail truoc
                Dim a = (From q In data.BanHangDetails Where q.BanHangId = p.Id).ToList
                For Each b In a
                    data.BanHangDetails.DeleteObject(b)
                Next
                data.SaveChanges()

                'lưu thông tin cho OrderDetail
                If hidID.Value <> "0" Then
                    Try
                        Dim index As Integer = 0
                        Dim GrossAmount As Integer = 0
                        For i As Integer = 0 To hidRowIndex.Value - 1
                            Dim strMaterialCode As String = ""
                            Dim strUnit As String = ""
                            Dim intAmount As Integer = 0

                            Dim txtMaterialCode As String = "txtChoice" + i.ToString
                            If Request.Form(txtMaterialCode) <> Nothing AndAlso Request.Form(txtMaterialCode).ToString.Trim() <> "" Then
                                strMaterialCode = Request.Form(txtMaterialCode)
                            End If

                            If (strMaterialCode.Trim <> "") Then

                                Dim txtAmount As String = "txtAmount" + i.ToString
                                If Request.Form(txtAmount) <> Nothing AndAlso Request.Form(txtAmount).ToString.Trim() <> "" AndAlso Request.Form(txtAmount).ToString.Trim() <> "0" Then
                                    Try
                                        intAmount = Integer.Parse(Request.Form(txtAmount))
                                    Catch ex As Exception
                                        intAmount = 0
                                    End Try
                                End If


                                If (intAmount <> 0) Then

                                    'Luu xuong Order Detail
                                    Dim intVSId As Integer = (From q In data.Products Where q.Code = strMaterialCode Select q.ProductId).FirstOrDefault
                                    Dim intPrice As Integer = (From q In data.Products Where q.Code = strMaterialCode Select q.SellPrice).FirstOrDefault

                                    Dim od As New BanHangDetail
                                    od.BanHangId = CInt(hidID.Value)
                                    od.ProductId = intVSId
                                    od.ProductCode = strMaterialCode
                                    od.Number = intAmount

                                    GrossAmount += intAmount * intPrice
                                    od.GrossAmount = intAmount * intPrice

                                    data.BanHangDetails.AddObject(od)

                                    data.SaveChanges()
                                    index = index + 1

                                End If
                            End If
                        Next
                        p.GrossAmount = GrossAmount
                        data.SaveChanges()
                        'logInfo = "Insert OrderDetail of Order: " & txtDoc_serial_no.Text & "<br>" & logInfo
                        ' Insert_App_Log(logInfo, Function_Name.Order, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                        Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/Banhang/Detail.aspx?ID=" & hidID.Value & "';", Me.Page, True)



                    Catch ex As Exception

                        Excute_Javascript("Alertbox('Cập nhật chi tiết bán hàng thất bại.');", Me.Page, True)
                        Exit Sub
                    End Try
                End If
            Catch ex As Exception

                Excute_Javascript("Alertbox('Cập nhật Bán hàng thất bại.');", Me.Page, True)
            End Try
            '    End If
            'End If
        End Using
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("List.aspx")
    End Sub
End Class
